{% extends "base.html" %}

{% block title %}搜索结果 - 畅读小说网{% endblock %}

{% block content %}
<style>
    /* 整体容器样式 */
   .search-container {
        max-width: 1200px;
        margin: 0 auto;
        padding: 20px;
    }

    /* 搜索头部样式 */
   .search-header {
        text-align: center;
        margin-bottom: 40px;
    }

   .search-header h1 {
        font-size: 2.5rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 20px;
    }

   .search-box form {
        display: flex;
        justify-content: center;
        align-items: center;
    }

   .search-box input[type="text"] {
        width: 300px;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px 0 0 5px;
        outline: none;
    }

   .search-box button {
        padding: 10px 20px;
        background-color: #007BFF;
        color: white;
        border: none;
        border-radius: 0 5px 5px 0;
        cursor: pointer;
    }

   .search-box button:hover {
        background-color: #0056b3;
    }

    /* 搜索结果摘要样式 */
   .result-summary {
        font-size: 1.1rem;
        color: #666;
        margin-bottom: 20px;
    }

    /* 筛选选项样式 */
   .filter-options {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
    }

   .filter-group {
        display: flex;
        align-items: center;
    }

   .filter-group label {
        margin-right: 10px;
        font-weight: bold;
        color: #333;
    }

   .filter-select {
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 5px;
        outline: none;
    }

    /* 小说列表样式 */
   .novel-list {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
    }

   .search-novel-item {
        display: flex;
        gap: 20px;
        background-color: #fff;
        border: 1px solid #eee;
        border-radius: 5px;
        padding: 20px;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }

   .novel-cover {
        width: 100px;
        height: 150px;
        position: relative;
        overflow: hidden;
    }

   .novel-cover img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

   .no-cover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f0f0f0;
        color: #999;
    }

   .novel-info {
        flex: 1;
    }

   .novel-title {
        font-size: 1.3rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
    }

   .novel-title a {
        color: #333;
        text-decoration: none;
    }

   .novel-title a:hover {
        color: #007BFF;
    }

   .novel-meta {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 10px;
        color: #666;
    }

   .novel-desc {
        color: #666;
        line-height: 1.6;
        margin-bottom: 10px;
    }

   .novel-stats {
        display: flex;
        gap: 10px;
        color: #666;
        margin-bottom: 10px;
    }

   .stat-item {
        display: flex;
        align-items: center;
    }

   .icon-chapters::before {
        content: '📖';
        margin-right: 5px;
    }

   .icon-views::before {
        content: '👀';
        margin-right: 5px;
    }

   .icon-bookshelf::before {
        content: '📚';
        margin-right: 5px;
    }

   .novel-actions {
        display: flex;
        gap: 10px;
    }

   .btn-detail,
   .btn-read,
   .btn-add-bookshelf,
   .btn-remove-bookshelf,
   .btn.btn-primary,
   .page-link {
        padding: 8px 16px;
        border-radius: 5px;
        text-decoration: none;
        display: inline-block;
        background-color: #007BFF;
        color: white;
    }

   .btn-detail:hover,
   .btn-read:hover,
   .btn-add-bookshelf:hover,
   .btn-remove-bookshelf:hover,
   .btn.btn-primary:hover,
   .page-link:hover {
        background-color: #0056b3;
    }

    /* 分页样式 */
   .pagination {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 40px;
    }

   .page-info {
        color: #666;
    }

   .page-links {
        display: flex;
        gap: 10px;
    }

   .page-link.current {
        background-color: #0056b3;
    }

    /* 无结果样式 */
   .empty-results {
        text-align: center;
        margin-top: 40px;
    }

   .empty-icon {
        font-size: 3rem;
        color: #999;
        margin-bottom: 20px;
    }

   .empty-results h3 {
        font-size: 1.5rem;
        font-weight: bold;
        color: #333;
        margin-bottom: 10px;
    }

   .empty-results p {
        color: #666;
        margin-bottom: 20px;
    }
</style>
<div class="search-container">
    <div class="search-header">
        <h1>搜索结果</h1>
        <div class="search-box">
            <form action="{% url 'novel_search' %}" method="get">
                <input type="text" name="q" placeholder="搜索小说名或作者..." value="{{ query }}">
                <button type="submit">搜索</button>
            </form>
        </div>
    </div>

    <div class="search-results">
        <div class="result-summary">
            {% if query %}
                <p>关键词 "<strong>{{ query }}</strong>" 的搜索结果：共找到 <strong>{{ paginator.count }}</strong> 条结果</p>
            {% else %}
                <p>请输入关键词进行搜索</p>
            {% endif %}
        </div>

        <div class="filter-options">
            <div class="filter-group">
                <label>筛选：</label>
                <select id="category-filter" class="filter-select">
                    <option value="">全部分类</option>
                    {% for category in categories %}
                    <option value="{{ category.id }}" {% if category_id == category.id|stringformat:"i" %}selected{% endif %}>{{ category.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="filter-group">
                <label>排序：</label>
                <select id="sort-filter" class="filter-select">
                    <option value="relevance" {% if sort_by == 'relevance' or not sort_by %}selected{% endif %}>相关度</option>
                    <option value="newest" {% if sort_by == 'newest' %}selected{% endif %}>最新发布</option>
                    <option value="popular" {% if sort_by == 'popular' %}selected{% endif %}>人气最高</option>
                </select>
            </div>
        </div>

        {% if novels %}
        <div class="novel-list">
            {% for novel in novels %}
            <div class="search-novel-item">
                <div class="novel-cover">
                    <a href="{% url 'novel_detail' novel.id %}">
                        {% if novel.cover %}
                            <img src="{{ novel.cover.url }}" alt="{{ novel.title }}">
                        {% else %}
                            <div class="no-cover">暂无封面</div>
                        {% endif %}
                    </a>
                </div>
                <div class="novel-info">
                    <h3 class="novel-title">
                        <a href="{% url 'novel_detail' novel.id %}">{{ novel.title }}</a>
                    </h3>
                    <div class="novel-meta">
                        <span class="novel-author">作者：{{ novel.author.username }}</span>
                        <span class="novel-category">分类：{{ novel.category.name }}</span>
                        <span class="novel-status">状态：{{ novel.get_status_display }}</span>
                        <span class="novel-date">发布时间：{{ novel.created_at|date:"Y-m-d" }}</span>
                    </div>
                    <p class="novel-desc">{{ novel.description|truncatechars:200 }}</p>
                    <div class="novel-stats">
                        <span class="stat-item"><i class="icon-chapters"></i>{{ novel.chapters.count }}章</span>
                        <span class="stat-item"><i class="icon-views"></i>{{ novel.views|default:0 }}阅读</span>
                        <span class="stat-item"><i class="icon-bookshelf"></i>{{ novel.in_bookshelves.count }}收藏</span>
                    </div>
                    <div class="novel-actions">
                        <a href="{% url 'novel_detail' novel.id %}" class="btn-detail">查看详情</a>
                        <a href="{% url 'read_novel' novel.id %}" class="btn-read">开始阅读</a>
                        {% if user.is_authenticated %}
                            {% if novel.id in user_bookshelf_novels %}
                                <a href="javascript:void(0);" class="btn-remove-bookshelf" data-novel-id="{{ novel.id }}">已收藏</a>
                            {% else %}
                                <a href="javascript:void(0);" class="btn-add-bookshelf" data-novel-id="{{ novel.id }}">加入书架</a>
                            {% endif %}
                        {% endif %}
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>

        {% if is_paginated %}
        <div class="pagination">
            <span class="page-info">第 {{ page_obj.number }} 页 / 共 {{ page_obj.paginator.num_pages }} 页</span>
            <div class="page-links">
                {% if page_obj.has_previous %}
                <a href="?q={{ query }}&{% if category_id %}category={{ category_id }}&{% endif %}{% if sort_by %}sort={{ sort_by }}&{% endif %}page=1" class="page-link">&laquo; 首页</a>
                <a href="?q={{ query }}&{% if category_id %}category={{ category_id }}&{% endif %}{% if sort_by %}sort={{ sort_by }}&{% endif %}page={{ page_obj.previous_page_number }}" class="page-link">&lt; 上一页</a>
                {% endif %}

                {% for num in page_obj.paginator.page_range %}
                    {% if page_obj.number == num %}
                    <span class="page-link current">{{ num }}</span>
                    {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    <a href="?q={{ query }}&{% if category_id %}category={{ category_id }}&{% endif %}{% if sort_by %}sort={{ sort_by }}&{% endif %}page={{ num }}" class="page-link">{{ num }}</a>
                    {% endif %}
                {% endfor %}

                {% if page_obj.has_next %}
                <a href="?q={{ query }}&{% if category_id %}category={{ category_id }}&{% endif %}{% if sort_by %}sort={{ sort_by }}&{% endif %}page={{ page_obj.next_page_number }}" class="page-link">下一页 &gt;</a>
                <a href="?q={{ query }}&{% if category_id %}category={{ category_id }}&{% endif %}{% if sort_by %}sort={{ sort_by }}&{% endif %}page={{ page_obj.paginator.num_pages }}" class="page-link">末页 &raquo;</a>
                {% endif %}
            </div>
        </div>
        {% endif %}

        {% else %}
            {% if query %}
            <div class="empty-results">
                <div class="empty-icon">🔍</div>
                <h3>未找到相关小说</h3>
                <p>没有找到与 "{{ query }}" 相关的小说，请尝试其他关键词。</p>
                <a href="{% url 'novel_list' %}" class="btn btn-primary">浏览全部小说</a>
            </div>
            {% endif %}
        {% endif %}
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 分类筛选
        const categoryFilter = document.getElementById('category-filter');
        categoryFilter.addEventListener('change', updateFilters);

        // 排序方式
        const sortFilter = document.getElementById('sort-filter');
        sortFilter.addEventListener('change', updateFilters);

        // 更新筛选条件并刷新页面
        function updateFilters() {
            const query = '{{ query }}';
            const category = categoryFilter.value;
            const sort = sortFilter.value;

            let url = '{% url "novel_search" %}?q=' + encodeURIComponent(query);

            if (category) {
                url += '&category=' + category;
            }

            if (sort) {
                url += '&sort=' + sort;
            }

            window.location.href = url;
        }

        // 添加/移除书架
        const addButtons = document.querySelectorAll('.btn-add-bookshelf');
        const removeButtons = document.querySelectorAll('.btn-remove-bookshelf');

        addButtons.forEach(button => {
            button.addEventListener('click', function() {
                const novelId = this.getAttribute('data-novel-id');
                addToBookshelf(novelId, this);
            });
        });

        removeButtons.forEach(button => {
            button.addEventListener('click', function() {
                const novelId = this.getAttribute('data-novel-id');
                removeFromBookshelf(novelId, this);
            });
        });

        function addToBookshelf(novelId, button) {
            fetch('/api/bookshelf/add_to_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: novelId
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 更改按钮样式和文本
                    button.textContent = '已收藏';
                    button.classList.remove('btn-add-bookshelf');
                    button.classList.add('btn-remove-bookshelf');
                    button.addEventListener('click', function() {
                        removeFromBookshelf(novelId, this);
                    });
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        function removeFromBookshelf(novelId, button) {
            fetch('/api/bookshelf/remove_from_bookshelf/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')
                },
                body: JSON.stringify({
                    novel_id: novelId
                })
            })
           .then(response => response.json())
           .then(data => {
                if (data.detail) {
                    // 更改按钮样式和文本
                    button.textContent = '加入书架';
                    button.classList.remove('btn-remove-bookshelf');
                    button.classList.add('btn-add-bookshelf');
                    button.addEventListener('click', function() {
                        addToBookshelf(novelId, this);
                    });
                }
            })
           .catch(error => {
                console.error('Error:', error);
            });
        }

        // 获取CSRF Token
        function getCookie(name) {
            let cookieValue = null;
            if (document.cookie && document.cookie !== '') {
                const cookies = document.cookie.split(';');
                for (let i = 0; i < cookies.length; i++) {
                    const cookie = cookies[i].trim();
                    if (cookie.substring(0, name.length + 1) === (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    });
</script>
{% endblock %}    